package com.sls.core.util;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.sls.core.http.HttpClient;
import com.sls.game.dao.xingxitian.XingGameAreaSrvDAO;
import com.sls.game.pojo.xingqitian.XingDisCountInfo;
import com.sls.game.pojo.xingqitian.XingGameAreaSrvInfo;

@Component("autoUpdateASMsgTimer")
public class AutoUpdateASMsgTimer {

	private static Logger log = Logger.getLogger(AutoUpdateASMsgTimer.class);
	private static String filename = "xingasadd.properties";
	@Resource(name = "xingGameAreaSrvDAO")
	private XingGameAreaSrvDAO xingGameAreaSrvDAO;

	private HttpClient httpClient = new HttpClient();

	// public static void main(String[] args) {
	// ApplicationContext atc = new ClassPathXmlApplicationContext(
	// "applicationContext.xml");
	// AutoUpdateASMsgTimer auto = (AutoUpdateASMsgTimer) atc
	// .getBean("autoUpdateASMsgTimer");
	// AutoUpdateASMsgTimer au = new AutoUpdateASMsgTimer();
	// auto.updateASMsg();
	// }

	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public void updateASMsg() {
		log.info("定时更新星启天区服信息......");
		String gameidAddress = PropertiesUtil.getValue(
				"xing.interface.gameid.address", filename);
		String templateAddress = PropertiesUtil.getValue(
				"xing.interface.template.address", filename);
		List<XingDisCountInfo> gameids = null;
		gameids = sendGameidRequest(gameidAddress, gameids);
		// gameids = new ArrayList<XingDisCountInfo>();
		// XingDisCountInfo x = new XingDisCountInfo();
		// x.setRecordId("10");
		// gameids.add(x);

		sendASRequest(templateAddress, gameids);
		log.info("完成更新星启天区服信息......");
	}

	private void sendASRequest(String templateAddress,
			List<XingDisCountInfo> gameids) {
		List<XingGameAreaSrvInfo> asList = null;
		if (gameids != null && !gameids.isEmpty()) {
			for (XingDisCountInfo info : gameids) {
				String recordId = info.getRecordId();
				String tempAddress = templateAddress + recordId + ".xml";
				try {
					log.info("发送到星启天的区服模板文件请求参数为：" + tempAddress);
					String xml = httpClient.doGet(tempAddress, "GB2312");
					log.info("星启天的区服模板文件返回的结果参数为：" + xml);
					if (StringUtils.isNotEmpty(xml)) {
						asList = this.parse(xml, recordId);
						List<XingGameAreaSrvInfo> xasList = this.xingGameAreaSrvDAO
								.queryByGameType(recordId);
						if (xasList.isEmpty() || asList.isEmpty()) {
							continue;
						}
						int oldSize = xasList.size();
						int newSize = asList.size();
						int size = 0;
						if (oldSize <= newSize) {
							size = oldSize;
						} else {
							size = newSize;
						}
						for (int i = 0; i < size; i++) {
							String id = xasList.get(i).getId();
							XingGameAreaSrvInfo asInfo = asList.get(i);
							asInfo.setId(id);
							asInfo.setInsertTime(ServerDateAndTime
									.getNowDateTimeOfFormat());
							this.xingGameAreaSrvDAO.updateAS(asInfo);
						}
					}
				} catch (Exception e) {
					log.error("更新星启天的区服模板文件异常！", e);
					continue;
				}
			}
		}
	}

	private List<XingDisCountInfo> sendGameidRequest(String gameidAddress,
			List<XingDisCountInfo> gameids) {
		try {
			log.info("发送到星启天的gameid文件请求参数为：" + gameidAddress);
			String str = httpClient.doGet(gameidAddress, "GB2312");
			log.info("星启天的gameid文件返回的结果参数为：" + str);
			if (StringUtils.isNotEmpty(str)) {
				gameids = this.parseGameIdXml(str);
			}
		} catch (Exception e) {
			log.error("请求星启天的gameid文件异常！", e);
		}
		return gameids;
	}

	/**
	 * 解析星启天gameid.xml
	 * 
	 * @param file
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<XingDisCountInfo> parseGameIdXml(String xml) {
		List<XingDisCountInfo> records = new ArrayList<XingDisCountInfo>();
		Document document = null;
		Element root = null;
		try {
			// 读取XML文件,获得document对象
			document = DocumentHelper.parseText(xml);
			root = document.getRootElement();
			Element secondEle = root.element("records");
			Element thirdEle = null;
			Iterator<Element> it = secondEle.elementIterator();
			while (it.hasNext()) {
				thirdEle = it.next();
				if (thirdEle != null) {
					String tagName = thirdEle.getName();
					if ("record".equals(tagName)) {
						Iterator<Element> it2 = thirdEle.elementIterator();
						XingDisCountInfo record = new XingDisCountInfo();
						while (it2.hasNext()) {
							Element fourEle = it2.next();
							if (fourEle != null) {
								String tagName2 = fourEle.getName();
								if ("game".equals(tagName2)) {
									String game = fourEle.getTextTrim();
									record.setRecordName(game);
								} else if ("id".equals(tagName2)) {
									String id = fourEle.getTextTrim();
									record.setRecordId(id);
								} else if ("salePrice".equals(tagName2)) {
									String salePrice = fourEle.getTextTrim();
									record.setRecordSalePrice(salePrice);
								} else if ("proid".equals(tagName2)) {
									String proid = fourEle.getTextTrim();
									record.setRecordProid(proid);
								}
							}
						}
						records.add(record);
					}
				}
			}
		} catch (DocumentException e) {
			log.error("解析gameid文件异常", e);
		}

		return records;
	}

	/**
	 * 解析星启天提供的xml模板文件
	 * 
	 * @param file
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<XingGameAreaSrvInfo> parse(String xml, String gametype) {
		List<XingGameAreaSrvInfo> list = null;
		Document document = null;
		Element root = null;
		try {
			document = DocumentHelper.parseText(xml); // 读取XML文件,获得document对象
			root = document.getRootElement();
			Iterator<Element> it = root.elementIterator();
			Element secondEle = null;
			while (it.hasNext()) {
				secondEle = it.next();
				if (secondEle != null) {
					String tagName = secondEle.getName();
					if ("gametype1".equals(tagName)) {// 二级节点
					} else if ("gamearea_s".equals(tagName)) {// 二级节点
						// 解析二级节点gamearea_s
						list = parseSecondGameAreas(secondEle, gametype);
					}
				}
			}
		} catch (Exception ex) {
			log.error("解析xml模板异常", ex);
		}
		return list;
	}

	/**
	 * 解析二级节点gamearea_s
	 * 
	 * @param secondEle
	 * @param gametype1
	 * @return
	 */
	@SuppressWarnings("unchecked")
	private List<XingGameAreaSrvInfo> parseSecondGameAreas(Element secondEle,
			String gametype1) {
		List<XingGameAreaSrvInfo> list = new ArrayList<XingGameAreaSrvInfo>();
		Iterator<Element> it = secondEle.elementIterator();
		Element thirdNodeEle = null;
		Element fourNodeEle = null;
		Element fiveNodeEle = null;
		Element sixNodeEle = null;
		XingGameAreaSrvInfo gameAreaInfo = null;
		int index = 0;
		while (it.hasNext()) {
			thirdNodeEle = it.next();
			if (thirdNodeEle != null) {
				String tagName = thirdNodeEle.getName();
				if ("gamearea".equals(tagName)) {
					Iterator<Element> it2 = thirdNodeEle.elementIterator();
					String areaId = "";
					String areaName = "";
					while (it2.hasNext()) {
						fourNodeEle = it2.next();
						String tagName2 = fourNodeEle.getName();
						if ("name".equals(tagName2)) {
							areaName = fourNodeEle.getTextTrim();
						} else if ("id".equals(tagName2)) {
							areaId = fourNodeEle.getTextTrim();
						} else if ("gamesrv_s".equals(tagName2)) {
							index++;
							Iterator<Element> iter = fourNodeEle
									.elementIterator();
							if (iter.hasNext()) {
								while (iter.hasNext()) {
									fiveNodeEle = iter.next();
									if (fiveNodeEle != null) {
										String tagName3 = fiveNodeEle.getName();
										if ("gamesrv".equals(tagName3)) {
											Iterator<Element> iterator = fiveNodeEle
													.elementIterator();
											gameAreaInfo = new XingGameAreaSrvInfo();
											gameAreaInfo
													.setGametype1(gametype1);
											gameAreaInfo.setAreaId(areaId);
											gameAreaInfo.setAreaName(areaName);
											while (iterator.hasNext()) {
												sixNodeEle = iterator.next();
												if (sixNodeEle != null) {
													String tagName4 = sixNodeEle
															.getName();
													if ("name".equals(tagName4)) {
														String name = sixNodeEle
																.getTextTrim();
														gameAreaInfo
																.setSrvName(name);
													} else if ("id"
															.equals(tagName4)) {
														String id = sixNodeEle
																.getTextTrim();
														gameAreaInfo
																.setSrvId(id);
													}
												}
											}
											list.add(gameAreaInfo);
										}
									}
								}
							}
						}
					}
					if (index <= 0) {
						gameAreaInfo = new XingGameAreaSrvInfo();
						gameAreaInfo.setGametype1(gametype1);
						gameAreaInfo.setAreaId(areaId);
						gameAreaInfo.setAreaName(areaName);
						list.add(gameAreaInfo);
					}
				}
			}
		}
		return list;
	}
}
